package com.apes.scm.supplier.baturu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.PredicateBuilder;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.StringUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service("baturuAccountInfoErpService")
public class BaturuAccountInfoErpService extends DomainService {

    @Autowired
    private EnumerationRepository enumerationRepository;
    @Autowired
    private StoreRepository storeRepository;

    public JSONObject create(SimpleRequest request) {
        JSONObject getJO = request.getJO();

        // 发送到供应商平台保存
        Object obj = invoke("sp.baturuAccountInfoService.supplier.create", this.appendBaturuAccountInfo(getJO));
        JSONObject reponseData = JSONObject.parseObject(obj.toString());
        if (!reponseData.getJSONObject("header").getString("code").equals("success")) throw new RuntimeException(reponseData.getJSONObject("header").getString("message"));
        JSONObject body = reponseData.getJSONObject("body");

        // 供应商平台的数据跟erp 平台主数据不一致，利用原来的数据返回
        getJO.put("id", body.get("id"));
        return getJO;
    }

    public JSONObject update(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        invoke("sp.baturuAccountInfoService.supplier.update", this.appendBaturuAccountInfo(getJO));

        // 利用原来得数据返回
        return getJO;
    }

    // erp 平台对象 和 supplier供应商平台对象不一致转换
    private Map appendBaturuAccountInfo(JSONObject getJO) {
        JSONObject accountStatus = getJO.getJSONObject("accountStatus");
        JSONObject storeNumber = getJO.getJSONObject("storeNumber");
        String storeId = storeNumber.getString("id");
        Store store = storeRepository.findOne(storeId);
        Enumeration enumeration = enumerationRepository.findOne(accountStatus.getString("id"));

        Map sendAccountInfoData = MapUtil.mapper("storeId", store.getOrigin(), "storeNumber", storeId,
                "baturuUniqueSign", getJO.get("baturuUniqueSign"),
                "mobilePhone", getJO.get("mobilePhone"),
                "accountStatus", MapUtil.mapper("code", enumeration.getCode()));
        if (!StringUtils.isEmpty(getJO.get("id"))) sendAccountInfoData.put("id", getJO.get("id"));
        return sendAccountInfoData;
    }

    // 自定义查询所有
    public Map findAll(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray condition = getJO.getJSONArray("condition");

        JSONObject reponse = new JSONObject();
        if (condition == null || condition.isEmpty()) { // 无条件
            reponse = JSONObject.parseObject(this.invoke("supp.baturuAccountInfoService.supplier.findAll", getJO));
        } else { // 有条件
            this.findCondiFormat(condition);
            reponse = JSONObject.parseObject(invoke("sp.baturuAccountInfoService.accordConditionFindAll", getJO));

        }

        JSONArray contents = reponse.getJSONObject("body").getJSONArray("content");
        long total = reponse.getJSONObject("body").getLong("total");
        this.supplierAccountInfoToErpAccountInfo(contents);
        return MapUtil.mapper("total", total, "pages", 1, "size", 9999, "elements", contents.size(), "page", 0, "content", contents);
    }

    // 供应商平台数据转换为 erp 平台对象
    private void supplierAccountInfoToErpAccountInfo(JSONArray contents) {
        contents.forEach(content -> {
            JSONObject changeContent = (JSONObject) content;
            JSONObject accountStatus = changeContent.getJSONObject("accountStatus");
            Enumeration enumeration = enumerationRepository.findByTypeAndCode("accountStatus", accountStatus.getString("code"));
            if (enumeration == null) enumeration = enumerationRepository.findByTypeAndDescription("accountStatus", accountStatus.getString("description"));
            changeContent.put("accountStatus", MapUtil.mapper("id", enumeration.getId(), "description", enumeration.getDescription()));

            String storeId = changeContent.getString("storeNumber");
            if (changeContent.get("storeNumber") instanceof Map) storeId = changeContent.getJSONObject("storeNumber").getString("id");
            Store store = storeRepository.findOne(storeId);
            changeContent.put("storeNumber", MapUtil.mapper("id", store.getId(), "name", store.getName()));
        });
    }


    // 查找条件格式化
    private void findCondiFormat(JSONArray conditionArray) {
        for (int i = 0; i < conditionArray.size(); i++) {
            String field = conditionArray.getJSONObject(i).getString("field");
            if (field.equals("accountStatus.id")) {
                Enumeration enumeration = enumerationRepository.findOne(conditionArray.getJSONObject(i).getString("value"));
                conditionArray.getJSONObject(i).put("value", enumeration.getCode());
                break;
            }

        }
    }
}
